package com.example.blog.modules.user.repository;

import com.example.blog.modules.user.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    /**
     * 根据用户名查找用户
     */
    Optional<User> findByUsername(String username);

    /**
     * 根据邮箱查找用户
     */
    Optional<User> findByEmail(String email);

    /**
     * 检查用户名是否存在
     */
    boolean existsByUsername(String username);

    /**
     * 检查邮箱是否存在
     */
    boolean existsByEmail(String email);

    /**
     * 根据用户名、邮箱或昵称模糊搜索用户
     */
    Page<User> findByUsernameContainingOrEmailContainingOrNicknameContaining(
            String username, String email, String nickname, Pageable pageable);

    /**
     * 统计指定时间段内的新增用户数
     */
    long countByCreatedAtAfter(LocalDateTime dateTime);

    /**
     * 统计最后登录时间在指定时间之后的用户数
     */
    long countByLastLoginTimeAfter(LocalDateTime dateTime);

    /**
     * 统计指定时间段内的用户数
     */
    long countByCreatedAtBetween(LocalDateTime startDate, LocalDateTime endDate);

    /**
     * 统计指定时间段内的活跃用户数
     */
    long countByLastLoginTimeBetween(LocalDateTime startDate, LocalDateTime endDate);

    /**
     * 获取每日新增用户数
     */
    @Query("SELECT DATE(u.createdAt) as date, COUNT(u) as count " +
           "FROM User u " +
           "WHERE u.createdAt BETWEEN :startDate AND :endDate " +
           "GROUP BY DATE(u.createdAt)")
    Map<String, Long> findDailyNewUsers(@Param("startDate") LocalDateTime startDate, 
                                      @Param("endDate") LocalDateTime endDate);
} 